package com.qiniu.data;

import java.util.Date;

import org.springframework.util.Assert;

import com.qiniu.util.Auth;

import lombok.Data;

/**
 * 七牛的基础配置环境
 */
@Data
public class QiniuEnv {
	private String accesskey;

	private String secretkey;

	private String bucket;

	private String dir;

	private String host;

	// token的有效时长
	private long expire;

	private Auth auth;

	// token的截止时间
	private long deadline;

	private String uptoken;

	public String getUptoken() {
		Assert.notNull(auth);
		if (this.deadline < new Date().getTime()) {
			// 重新设置token
			this.setUptoken(auth.uploadToken(bucket, null, expire, null));
		}
		return uptoken;
	}

	public void setUptoken(String uptoken) {
		Assert.notNull(expire);
		this.uptoken = uptoken;
		// 提前5分钟
		this.deadline = new Date().getTime() + expire - 5 * 60 * 100;
	}

	public void setAuth(Auth auth) {
		Assert.notNull(auth);
		Assert.notNull(bucket);
		Assert.notNull(expire);
		this.auth = auth;
		this.setUptoken(auth.uploadToken(bucket, null, expire, null));
	}
}
